package View;

import Domain.DomainController;
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JButton;
import javax.swing.JFrame;

/**
 *
 * @author kenneth
 */
public class DropBoxFrame extends JFrame implements ActionListener, WindowListener {

    JButton startServer;
    InfoArea infoArea; 
    DomainController dc;
    
    
    public DropBoxFrame() {
        this.setSize(400, 400);
        this.setTitle("Dropbox Server");
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        this.setLayout(new BorderLayout());
        this.initComponents();
        this.addComponents();
        dc = DomainController.getDomainController();
        this.setVisible(true);      
    }
    
    public void initComponents() {
        startServer = new JButton("Start");
        startServer.addActionListener(this);
        infoArea = new InfoArea();
    }
    
    public void addComponents() {
        this.add(infoArea,BorderLayout.CENTER);
        this.add(startServer,BorderLayout.SOUTH);
    }

    @Override
    public void actionPerformed(ActionEvent ae) {
        if(ae.getSource() == startServer) {
            if(startServer.getText().equals("Start")) {
                dc.startServer(infoArea);
                try {
                    //Initialiseren van de server is blijkbaar te traag waardoor het anders niet werkt
                    Thread.sleep(100);
                } catch (InterruptedException ex) {
                    Logger.getLogger(DropBoxFrame.class.getName()).log(Level.SEVERE, null, ex);
                }
                if(dc.serverIsRunning()) {
                    startServer.setText("Stop");
                }
            } else if(startServer.getText().equals("Stop")) {
                dc.stopServer();
                if(!dc.serverIsRunning()) {
                    startServer.setText("Start");
                }
            }
        }
    }

    @Override
    public void windowOpened(WindowEvent we) {
        
    }

    @Override
    public void windowClosing(WindowEvent we) {
        
    }

    @Override
    public void windowClosed(WindowEvent we) {
        dc.stopServer();
        System.exit(0);
    }

    @Override
    public void windowIconified(WindowEvent we) {
        
    }

    @Override
    public void windowDeiconified(WindowEvent we) {
        
    }

    @Override
    public void windowActivated(WindowEvent we) {
        
    }

    @Override
    public void windowDeactivated(WindowEvent we) {
        
    }
}
